package org.example.demo.service;

import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class StudentStorageService {
    private final Map<String, Map<String, Object>> students = new ConcurrentHashMap<>();
    private final Map<String, Map<String, Object>> certificates = new ConcurrentHashMap<>();

    public void addStudent(Map<String, Object> student) {
        students.put((String) student.get("studentId"), student);
    }

    public List<Map<String, Object>> getAllStudents() {
        return new ArrayList<>(students.values());
    }

    public void addCertificate(Map<String, Object> certificate) {
        // 验证必要字段
        String id = (String) certificate.get("id");
        if (id == null) {
            id = java.util.UUID.randomUUID().toString();
            certificate.put("id", id);
        }

        // 确保所有必要字段都存在
        ensureField(certificate, "studentId", "");
        ensureField(certificate, "certificateType", "");
        ensureField(certificate, "certificateNumber", "");
        ensureField(certificate, "issueDate", "");
        ensureField(certificate, "institution", "");
        
        // 确保 isValid 字段为 Boolean 类型
        if (!certificate.containsKey("isValid") || !(certificate.get("isValid") instanceof Boolean)) {
            certificate.put("isValid", Boolean.TRUE);
        }

        // 存储证书
        certificates.put(id, new HashMap<>(certificate));
    }

    private void ensureField(Map<String, Object> map, String field, Object defaultValue) {
        if (!map.containsKey(field) || map.get(field) == null) {
            map.put(field, defaultValue);
        }
    }

    public List<Map<String, Object>> getAllCertificates() {
        return new ArrayList<>(certificates.values());
    }

    public void updateCertificateStatus(String certificateId, boolean isValid) {
        Map<String, Object> certificate = certificates.get(certificateId);
        if (certificate != null) {
            certificate.put("isValid", Boolean.valueOf(isValid));
            certificates.put(certificateId, new HashMap<>(certificate));
        }
    }
} 